﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
//using System.Linq;
using System.Text;
using System.Windows.Forms;
using DBSourceToolsLib;
using System.Collections;
using WeifenLuo.WinFormsUI.Docking;
using System.Configuration;
using DBSourceToolsLib.Composite;


namespace DBSourceTools
{
    public partial class MainForm : Form, Interfaces.IWindowListObserver
        //,DBSourceToolsLib.Interfaces.ISourceEditorObserver
    {
        // TODO : recent projects
        private DBExplorer oDBExplorer;
        private SrvExplorer oServerExplorer = null;
        private SearchResultsForm m_SearchResultsForm;
        //private SortedList<string, DockContent> m_SourceList = new SortedList<string, DockContent>();
        private MainPanelForm m_CurrentSourceEditor;
 
        public MainForm()
        {
            this.Initialise();
            this.FormClosing += MainForm_FormClosing;
        }
        public MainForm(string strOpenFile)
        {
            this.Initialise();
            //this.NotifyEvent("Recent", "File", strOpenFile, DBSourceToolsLib.Interfaces.SourceEditorEvent.FileOpened, null);
        }
        private void Initialise()
        {
            InitializeComponent();
            oDBExplorer = new DBExplorer();
            WindowList.Instance().SetDockPanelMain(this.m_dockPanelMain);
            WindowList.Instance().RegisterInterestInWindowList(this);
        }

        private void MainForm_Load(object sender, EventArgs e)
        {
            this.Text = "DBSourceTools " + UserSettings.Instance().LastProjectConfigFile;

            WindowList.Instance().AddWindow("DBExplorer", oDBExplorer);

            //oDBExplorer.Show(this.m_dockPanelMain);
            //oDBExplorer.RegisterInterestInDbExplorer(this);

            UpdateToolStrip();

            m_SearchResultsForm = new SearchResultsForm("All", "Search", "Search");
            m_SearchResultsForm.SearchText = "";
            //m_SearchResultsForm.RegisterInterestInDbExplorer(this);
            //m_SearchResultsForm.RegisterInterestInSourceEditor(this);

            WindowList.Instance().AddWindow("All.Search.Search", m_SearchResultsForm);
            //this.m_SourceList.Add("All.Search.Search", m_SearchResultsForm);
            //m_SearchResultsForm.Show(this.m_dockPanelMain);

            m_SearchResultsForm.Hide();
            UpdateToobar_DatabaseList();

            Point oPoint = this.DesktopLocation;
        }

        private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            //MessageBox.Show("closing");
            if (UserSettings.Instance().ProjectNeedsSaving)
            {
                DialogResult result =
                    MessageBox.Show("This project file has been modified and needs to be saved.  Save Now ?",
                        "SaveProject",
                        MessageBoxButtons.YesNoCancel);
                if (result == DialogResult.Yes)
                {
                    
                    //UserSettings.Instance().
                    try
                    {
                        DBHelper oHelper = new DBHelper();
                        oHelper.SaveProject(this, false);
                        UserSettings.Instance().SaveConfig();
                    }
                    catch (Exception ex)
                    {
                        DBSourceToolsLib.SysObjects.UI.Forms.ErrorForm oError =
                            new DBSourceToolsLib.SysObjects.UI.Forms.ErrorForm(ex.ToString());
                        oError.ShowDialog(this);
                        e.Cancel = true;
                    }

                }
                else if (result == DialogResult.Cancel)
                {
                    e.Cancel = true;
                }
            }
        }

        private void UpdateToobar_DatabaseList()
        {
            m_toolStripComboBox_CurrentDB.Items.Clear();
            if (UserSettings.Instance().DatabaseProject != null)
            {
                foreach (SourceDatabase oSource in UserSettings.Instance().DatabaseProject.SourceDatabases)
                {
                    m_toolStripComboBox_CurrentDB.Items.Add(oSource.NickName);
                }
                if (UserSettings.Instance().CurrentDbNickName != null)
                    m_toolStripComboBox_CurrentDB.SelectedItem = UserSettings.Instance().CurrentDbNickName;
            }
        }

        private void UpdateToolStrip()
        {
            this.m_toolStripStatusLabel.Text = "Current Base Directory : " + UserSettings.Instance().ProjectBaseDirectory;

        }

        private void AddDeploymentTargetMenu(string strDatabase)
        {

        }

        private void DBExplorer_ObjectRename(string strDatabase, string strType, string strObject, string strParams)
        {
            string windowKey = "";
            if (strObject != null)
            {
                WindowList.Instance().RemoveWindow(strDatabase, strType, strObject);
                //windowKey = strDatabase + "." + strType + "." + strObject;

                //if (m_SourceList.ContainsKey(windowKey))
                //{
                //    // this window is visible and has been opened
                //    m_SourceList[windowKey].Close();
                //    m_SourceList.Remove(windowKey);
                //}

                switch (strType)
                {
                    case "Deployment Targets":
                        {
                            string newWindowKey = strDatabase + "." + strType + "." + strParams;
                            DatabaseForm odtForm = new DatabaseForm(strDatabase, strType, strParams);
                            //odtForm.RegisterInterestInSourceEditor(this);

                            WindowList.Instance().AddWindow(newWindowKey, odtForm);
                            //this.m_SourceList.Add(newWindowKey, odtForm);

                            odtForm.Show(this.m_dockPanelMain);
                        }
                        break;
                    case "Database":
                        {
                            string newWindowKey = strParams + "." + strType + ".Database";
                            DatabaseForm odtForm = new DatabaseForm(strParams, strType, "Database");
                            //odtForm.RegisterInterestInSourceEditor(this);
                            WindowList.Instance().AddWindow(newWindowKey, odtForm);
                            //this.m_SourceList.Add(newWindowKey, odtForm);
                            odtForm.Show(this.m_dockPanelMain);
                        }
                        break;

                    default:
                        {
                            MessageBox.Show("Default case not handled");
                            //SourceEditor oSourceEditor = new SourceEditor(strDatabase, strType, strParams);
                            //oSourceEditor.RegisterInterestInSourceEditor(this);
                            //string newWindowKey = strDatabase + "." + strType + "." + strParams;
                            //this.m_SourceList.Add(newWindowKey, oSourceEditor);
                            //oSourceEditor.Show(this.m_dockPanelMain);
                        }
                        break;

                }

            }

        }

        private void DBExplorer_SelectChanged(string strDatabase, string strType, string strObject, string strParams)
        {
            string windowKey = "";
            if (strObject != null)
            {
                windowKey = strDatabase + "." + strType + "." + strObject;

                if (WindowList.Instance().HasWindow(strDatabase, strType, strObject))
                {
                    WindowList.Instance().FocusWindow(strDatabase, strType, strObject, strParams);
                    #region oldcode
                    //this.m_SourceList[windowKey].Focus();
                    //// check for a change of line number
                    //if (!String.IsNullOrEmpty(strParams))
                    //{
                    //    switch (strType)
                    //    {
                    //        case "File":
                    //            int iLine;
                    //            if (Int32.TryParse(strParams, out iLine))
                    //            {
                    //                TextEditorForm oTextForm = (TextEditorForm)m_SourceList[windowKey];
                    //                oTextForm.GotoLine(iLine);
                    //            }
                    //            break;
                    //    }
                    //}
                    #endregion
                }
                else
                {
                    this.Cursor = Cursors.WaitCursor;
                    switch (strType)
                    {
                        case "Dependency Tree":
                            DependencyTreeForm oDepTreeForm = new DependencyTreeForm(strDatabase, strType, strObject);
                            //oDepTreeForm.RegisterInterestInSourceEditor(this);
                            WindowList.Instance().AddWindow(windowKey, oDepTreeForm);
                            //this.m_SourceList.Add(windowKey, oDepTreeForm);
                            oDepTreeForm.Show(this.m_dockPanelMain);
                            break;
                        case "Deployment Targets":
                        case "Database":
                            
                            DatabaseForm odtForm = new DatabaseForm(strDatabase, strType, strObject);
                            //odtForm.RegisterInterestInSourceEditor(this);
                            WindowList.Instance().AddWindow(windowKey, odtForm);
                            //this.m_SourceList.Add(windowKey, odtForm);
                            odtForm.Show(this.m_dockPanelMain);
                            break;
                        case "Data":
                            {
                                DataForm oDataForm = new DataForm(strDatabase, "Data", strObject);
                                //oDataForm.RegisterInterestInSourceEditor(this);
                                WindowList.Instance().AddWindow(windowKey, oDataForm);
                                //this.m_SourceList.Add(windowKey, oDataForm);
                                oDataForm.Show(this.m_dockPanelMain);
                            }
                            break;
                        case "File":
                            {
                                if (System.IO.File.Exists(strObject))
                                {
                                    TextEditorForm oTextForm = new TextEditorForm(strDatabase, strType, strObject
                                        ,DBSourceToolsLib.SysObjects.QueryType.NewQuery, strParams);
                                    //oTextForm.RegisterInterestInSourceEditor(this);
                                    WindowList.Instance().AddWindow(windowKey, oTextForm);

                                    //this.m_SourceList.Add(windowKey, oTextForm);
                                    oTextForm.Show(this.m_dockPanelMain);
                                }
                                else
                                {
                                    UserSettings.Instance().RemoveRecentFile(strObject);
                                    this.oDBExplorer.UpdateTreeViewDatabases();
                                    UserSettings.Instance().SaveRecentFileList();
                                }
                            }
                            break;
                        case "Queries":
                            {
                                SourceDatabase oSource = UserSettings.Instance().getSourceDatabase(strDatabase);

                                string strNewQueryName = oSource.BaseDirectory + "\\Queries\\" +
                                    strObject + ".sql";

                                TextEditorForm oTextForm = new TextEditorForm(strDatabase, strType, strNewQueryName
                                    , DBSourceToolsLib.SysObjects.QueryType.NewQuery, strParams);
                                //oTextForm.RegisterInterestInSourceEditor(this);
                                WindowList.Instance().AddWindow(windowKey, oTextForm);
                                //this.m_SourceList.Add(windowKey, oTextForm);
                                oTextForm.Show(this.m_dockPanelMain);
                            }

                            break;
                        case "CompareResults":
                            {
                                CompareResultsForm oResultsform = new CompareResultsForm(strDatabase, strType, strObject);
                                oResultsform.TargetDatabaseNick = strParams;
                                //oResultsform.RegisterInterestInSourceEditor(this);
                                WindowList.Instance().AddWindow(windowKey, oResultsform);
                                //this.m_SourceList.Add(windowKey, oResultsform);
                                oResultsform.Show(this.m_dockPanelMain);
                            }
                            break;
                        default:
                            MessageBox.Show("default case not handled");
                            //SourceEditor oSourceEditor = new SourceEditor(strDatabase, strType, strObject);
                            //oSourceEditor.RegisterInterestInSourceEditor(this);

                            //this.m_SourceList.Add(windowKey, oSourceEditor);
                            //oSourceEditor.Show(this.m_dockPanelMain);

                            break;
                    }
                    this.Cursor = Cursors.Default;
                }
            }
            else
            {
                if (strType != null)
                {
                    windowKey = strDatabase + "." + strType;
                }
                else
                {
                    windowKey = strDatabase;
                }
            }
        }



        private void toolStripButton1_Click(object sender, EventArgs e)
        {
            this.oDBExplorer.Show();
        }

        private void databaseExplorerToolStripMenuItem_Click(object sender, EventArgs e)
        {
//            if (this.oDBExplorer.IsHidden)
                this.oDBExplorer.Show();
            //else
            //    this.oDBExplorer.Hide();

        }

        private void btnNewQuery_Click(object sender, EventArgs e)
        {

        }


        #region IDBExplorerObserver Members

        //public void NotifyEvent(string strDatabase, string strType, string strObject,
        //    DBSourceToolsLib.Interfaces.DBExplorerObserverEvent oEvent, string strParams)
        //{
        //    switch (oEvent)
        //    {
        //        case DBSourceToolsLib.Interfaces.DBExplorerObserverEvent.ObjectRename:
        //            DBExplorer_ObjectRename(strDatabase, strType, strObject, strParams);
        //            break;
        //        case DBSourceToolsLib.Interfaces.DBExplorerObserverEvent.SelectChanged:
        //            DBExplorer_SelectChanged(strDatabase, strType, strObject, strParams);
        //            break;
        //        case DBSourceToolsLib.Interfaces.DBExplorerObserverEvent.CurrentDBChanged:
        //            UpdateToobar_CurrentDatabase(strDatabase);
        //            break;
        //        case DBSourceToolsLib.Interfaces.DBExplorerObserverEvent.FileDeleted:
        //            WindowList.Instance().RemoveWindow(strDatabase, strType, strObject);
        //            //string windowKey = strDatabase + "." + strType + "." + strObject;
        //            //if (m_SourceList.ContainsKey(windowKey))
        //            //{
        //            //    // this window is visible and has been opened
        //            //    m_SourceList[windowKey].Close();
        //            //    m_SourceList.Remove(windowKey);
        //            //}
        //            break;
        //    }
        //}

        private void UpdateToobar_CurrentDatabase(string strDatabase)
        {
            //throw new NotImplementedException();
            m_toolStripComboBox_CurrentDB.SelectedItem = strDatabase;
        }
        #endregion

        #region ISourceEditorObserver Members

        //public void NotifyEvent(string strDatabase, string strType, string strObject
        //    , DBSourceToolsLib.Interfaces.SourceEditorEvent oEvent, string strParams)
        //{
        //    string message = strDatabase + "." + strType + "." + strObject;
        //    switch (oEvent)
        //    {
        //        case DBSourceToolsLib.Interfaces.SourceEditorEvent.Close:
        //            {
        //                //if (this.m_SourceList.ContainsKey(message))
        //                //{
        //                //    this.m_SourceList.Remove(message);
        //                //}
        //            }
        //            break;
        //        case DBSourceToolsLib.Interfaces.SourceEditorEvent.IsCurrent:
        //            {
        //                //if (this.m_SourceList.ContainsKey(message))
        //                //    this.m_CurrentSourceEditor = (MainPanelForm)this.m_SourceList[message];
        //            }
        //            break;
        //        case DBSourceToolsLib.Interfaces.SourceEditorEvent.Deleted:
        //            {
        //                if (strObject.CompareTo("Database") == 0)
        //                    oDBExplorer.UpdateTreeViewDatabases();
        //                else
        //                    oDBExplorer.UpdateTreeView(strDatabase);
        //            }
        //            break;
        //        case DBSourceToolsLib.Interfaces.SourceEditorEvent.Rename:
        //            {
        //                this.DBExplorer_ObjectRename(strDatabase, strType, strObject, strParams);
        //                oDBExplorer.UpdateTreeView(strDatabase);
        //            }
        //            break;
        //        case DBSourceToolsLib.Interfaces.SourceEditorEvent.DBRename:
        //            {
        //                this.DBExplorer_ObjectRename(strDatabase, strType, strObject, strParams);
        //                oDBExplorer.UpdateTreeViewDatabases();
        //            }
        //            break;
        //        case DBSourceToolsLib.Interfaces.SourceEditorEvent.FileOpened:
        //            {
        //                this.DBExplorer_SelectChanged(strDatabase, strType, strObject, null);
        //                UserSettings.Instance().AddRecentFile(strObject);
        //                //oDBExplorer.UpdateTreeViewDatabases();
        //            }
        //            break;
        //        case DBSourceToolsLib.Interfaces.SourceEditorEvent.TargetDeleted:
        //            {
        //                this.oDBExplorer.UpdateTreeViewDatabases();
        //            }
        //            break;

        //    }
        //}

        #endregion

        private void openToolStripMenuItem_Click(object sender, EventArgs e)
        {
            m_openFileDialog1.Filter = "";
            if (this.m_openFileDialog1.ShowDialog(this) == DialogResult.OK)
            {
                //UserSettings.Instance().ClearDatabases();
                //UserSettings.Instance().DatabaseXmlFile = this.m_openFileDialog1.FileName;
                //UserSettings.Instance().LoadDatabasesEx(UserSettings.Instance().ProjectBaseDirectory, UserSettings.Instance().DatabaseXmlFile);
                oDBExplorer.UpdateTreeViewDatabases();
            }
        }

        private void setBaseDirectoryToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (this.m_folderBrowserDialog1.ShowDialog(this) == DialogResult.OK)
            {
                //UserSettings.Instance().ProjectBaseDirectory = this.m_folderBrowserDialog1.SelectedPath;
                //UserSettings.Instance().ClearDatabases();
                //UserSettings.Instance().LoadDatabasesEx(UserSettings.Instance().ProjectBaseDirectory, UserSettings.Instance().DatabaseXmlFile);
                //oDBExplorer.UpdateTreeViewDatabases();

            }
        }

        private void saveSettingsToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                SaveConfigSettings();
            }
            catch (Exception ex)
            {
                DBSourceToolsLib.SysObjects.UI.Forms.ErrorForm oError =
                    new DBSourceToolsLib.SysObjects.UI.Forms.ErrorForm(ex.ToString());
                oError.ShowDialog(this);

//                MessageBox.Show(ex.ToString());
            }
            //oConfig.AppSettings.Settings["BaseDirectory"].Value = UserSettings.Instance().BaseDirectory;
        }

        private void saveFileToolStripMenuItem_Click(object sender, EventArgs e)
        {
            MessageBox.Show("Mainform save");
        }

        private void clearRecentFileListToolStripMenuItem_Click(object sender, EventArgs e)
        {
            UserSettings.Instance().ClearRecentFiles();
            UserSettings.Instance().SaveRecentFileList();
            this.oDBExplorer.UpdateTreeViewDatabases();
        }


        private void SaveConfigSettings()
        {
            try
            {
                UserSettings.Instance().SaveConfig();
            }
            catch (Exception ex)
            {
                DBSourceToolsLib.SysObjects.UI.Forms.ErrorForm oError =
                    new DBSourceToolsLib.SysObjects.UI.Forms.ErrorForm(ex.ToString());
                oError.ShowDialog(this);

//                MessageBox.Show(ex.ToString());
            }
        }


        private void saveProjectToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                UserSettings.Instance().DatabaseProject.WriteProjectFile();

                DBSourceToolsLib.SourceDatabaseWriter oWriter = new SourceDatabaseWriter(this,
                    DBSourceToolsLib.Commands.DatabaseCommandTypes.WriteToDisk, UserSettings.Instance().DatabaseProject);

                SourceDatabase oSource = UserSettings.Instance().DatabaseProject.SourceDatabases[0];
                oWriter.Execute(ref oSource, null);
            } catch (Exception ex)
            {
                DBSourceToolsLib.SysObjects.UI.Forms.ErrorForm oError =
                    new DBSourceToolsLib.SysObjects.UI.Forms.ErrorForm(ex.ToString());
                oError.ShowDialog(this);

//                MessageBox.Show(ex.ToString());
            }


        }

        private void projectToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            //File | New | Project
            try
            {
                DBSourceToolsLib.DatabaseProjectUI.NewProjectForm oNewProjectForm
                    = new DBSourceToolsLib.DatabaseProjectUI.NewProjectForm();
                //            NewProjectForm oNewProject = new NewProjectForm();
                if (oNewProjectForm.ShowDialog(this) == DialogResult.OK)
                {

                    DBSourceToolsLib.DatabaseProject oNewProject = oNewProjectForm.GetDatabaseProject();
                    oNewProject.CreateBaseDirectories();
                    oNewProject.WriteProjectFile();
                    UserSettings.Instance().DatabaseProject = oNewProject;

                    this.oDBExplorer.UpdateTreeViewDatabases();
                    UserSettings.Instance().ProjectBaseDirectory = oNewProject.BaseDirectory;
                    UserSettings.Instance().SaveConfig();

                    if (MessageBox.Show(this, "Load Database" + oNewProject.SourceDatabases[0].NickName + " now ?",
                        "Load Database ", MessageBoxButtons.YesNo) == DialogResult.Yes)
                    {
                        this.Cursor = Cursors.WaitCursor;

                        DBSourceToolsLib.SourceDatabase oSource = oNewProject.SourceDatabases[0];

                        DBSourceToolsLib.SourceDatabaseLoader oSourceLoader =
                            new DBSourceToolsLib.SourceDatabaseLoader(this,
                                DBSourceToolsLib.Commands.DatabaseCommandTypes.LoadFromDatabase);

                        oSourceLoader.Execute(ref oSource, null);
                        oSourceLoader.HasErrors();
                        if (oSourceLoader.HasErrors())
                            throw new Exception(oSourceLoader.GetErrorMessage());

                        this.oDBExplorer.UpdateTreeView(oNewProject.SourceDatabases[0].NickName);
                        this.Cursor = Cursors.Default;
                    }

                }
            }  catch (Exception ex)
            {
                DBSourceToolsLib.SysObjects.UI.Forms.ErrorForm oError =
                    new DBSourceToolsLib.SysObjects.UI.Forms.ErrorForm(ex.ToString());
                oError.ShowDialog(this);

//                MessageBox.Show(ex.ToString());
            }


        }

        private void projectToolStripMenuItem2_Click(object sender, EventArgs e)
        {
            // File | Open | Project
            try
            {
                if (this.m_openProjectFileDialog1.ShowDialog(this) == DialogResult.OK)
                {
                    UserSettings.Instance().LastProjectConfigFile = this.m_openProjectFileDialog1.FileName;
                    UserSettings.Instance().LoadLastProjectConfigFile();
                    UpdateToolStrip();
                    SaveConfigSettings();
                    this.oDBExplorer.UpdateTreeViewDatabases();
                    //this.oDBExplorer.CurrentDatabase = UserSettings.Instance().DefaultDatabase;
                    for (int i = 0; i < UserSettings.Instance().DatabaseProject.SourceDatabases.Count; i++)
                    {
                        SourceDatabase oSourceDb = UserSettings.Instance().DatabaseProject.SourceDatabases[i];

                        DBSourceToolsLib.SourceDatabaseLoader oSourceLoader =
                            new DBSourceToolsLib.SourceDatabaseLoader(this,
                                DBSourceToolsLib.Commands.DatabaseCommandTypes.LoadFromDisk);

                        oSourceLoader.Execute(ref oSourceDb, null);
                        if (oSourceLoader.HasErrors())
                            throw new Exception(oSourceLoader.GetErrorMessage());

                        this.oDBExplorer.UpdateTreeView(oSourceDb.NickName);

                    }
                    UpdateToobar_DatabaseList();
                }
            }   catch (Exception ex)
            {
                DBSourceToolsLib.SysObjects.UI.Forms.ErrorForm oError =
                    new DBSourceToolsLib.SysObjects.UI.Forms.ErrorForm(ex.ToString());
                oError.ShowDialog(this);

//                MessageBox.Show(ex.ToString());
            }


        }


        private void deploymentTargetToolStripMenuItem1_Click(object sender, EventArgs e)
        {

        }

        private void saveToolStripMenuItem_Click(object sender, EventArgs e)
        {
            // File | Save Project
            try
            {
                DBHelper oHelper = new DBHelper();
                bool bRefreshData = MessageBox.Show("Refresh Data from Database ?", "Refresh Data", MessageBoxButtons.YesNo) == DialogResult.Yes;
                oHelper.SaveProject(this, bRefreshData);
                UserSettings.Instance().ProjectNeedsSaving = false;
                UserSettings.Instance().SaveConfig();
            }   catch (Exception ex)
            {
                DBSourceToolsLib.SysObjects.UI.Forms.ErrorForm oError =
                    new DBSourceToolsLib.SysObjects.UI.Forms.ErrorForm(ex.ToString());
                oError.ShowDialog(this);

//                MessageBox.Show(ex.ToString());
            }


        }

        private void saveAsToolStripMenuItem_Click(object sender, EventArgs e)
        {
            // File | Save Project As...

        }

        private void closeToolStripMenuItem_Click(object sender, EventArgs e)
        {
            // File | Close
        }

        private void exitToolStripMenuItem_Click(object sender, EventArgs e)
        {
            // File | Exit
            base.Close();
        }

        //private void queryToolStripMenuItem_Click(object sender, EventArgs e)
        //{
        //    // File | New | Query
        //    this.Cursor = Cursors.WaitCursor;
        //    SourceDatabase oSourceDb = UserSettings.Instance().getSourceDatabase(
        //            UserSettings.Instance().CurrentDbNickName
        //        );

        //    if (oSourceDb != null)
        //    {
        //        string strNewQueryName = oSourceDb.BaseDirectory + "\\Queries\\" +
        //            oSourceDb.SysObjects.NewQueryName();

        //        DBSourceToolsLib.SourceDatabaseLoader oLoader = new SourceDatabaseLoader(
        //            this, DBSourceToolsLib.Commands.DatabaseCommandTypes.NewQuery);

        //        oLoader.Execute(ref oSourceDb);

        //        this.oDBExplorer.UpdateTreeView(oSourceDb.NickName);

        //        TextEditorForm oTextForm = new TextEditorForm(oSourceDb.NickName, "Queries", strNewQueryName
        //            , DBSourceToolsLib.SysObjects.QueryType.NewQuery);
        //        oTextForm.RegisterInterestInSourceEditor(this);
        //        string strWindowKey = oSourceDb.NickName + ".Queries." + strNewQueryName;

        //        this.m_SourceList.Add(strWindowKey, oTextForm);
        //        oTextForm.Show(this.m_dockPanelMain);


        //        ////// we need to add a source view to this window as well.
        //        //SourceEditor oSourceEditor = new SourceEditor(this.oDBExplorer.m_CurrentDatabase.Name, "Queries", strNewQueryName);
        //        //oSourceEditor.RegisterInterestInSourceEditor(this);


        //        //this.m_SourceList.Add(strWindowKey, oSourceEditor);
        //        //oSourceEditor.Show(this.m_dockPanelMain);
        //    }

        //    this.Cursor = Cursors.Default;

        //}

        private void outputToolStripMenuItem_Click(object sender, EventArgs e)
        {
            // File | View | Search Results
            if (this.m_SearchResultsForm.IsHidden)
                this.m_SearchResultsForm.Show();
            else
                this.m_SearchResultsForm.Hide();
        }

        private void btnRunScript_Click(object sender, EventArgs e)
        {

        }

        private void fileToolStripMenuItem2_Click(object sender, EventArgs e)
        {
            // File | Open | File
            // find current dbname

            try
            {
                m_openFileDialog1.Filter = "";
                if (this.m_openFileDialog1.ShowDialog(this) == DialogResult.OK)
                {
                    if (m_openFileDialog1.FileName.EndsWith(".sdf"))
                    {
                        MessageBox.Show("DBSourceTools does not support SQL CE Databases");
                    }
                    else
                    {
                        // TODO : File | Open | File
                    }
                        //this.NotifyEvent( UserSettings.Instance().CurrentDbNickName
                        //    , "File", this.m_openFileDialog1.FileName, DBSourceToolsLib.Interfaces.SourceEditorEvent.FileOpened, null);
                }
            }   catch (Exception ex)
            {
                DBSourceToolsLib.SysObjects.UI.Forms.ErrorForm oError =
                    new DBSourceToolsLib.SysObjects.UI.Forms.ErrorForm(ex.ToString());
                oError.ShowDialog(this);

//                MessageBox.Show(ex.ToString());
            }


        }

        private void findInFilesToolStripMenuItem_Click(object sender, EventArgs e)
        {
            // Edit | Find in Files
            SearchForm oSearchForm = new SearchForm();
            if (oSearchForm.ShowDialog(this) == DialogResult.OK)
            {
                string strWindowKey = "All.Search.Search";
                if (WindowList.Instance().HasWindow("All","Search","Search"))
                //if (this.m_SourceList.ContainsKey(strWindowKey))
                {
                    m_SearchResultsForm.SearchText = oSearchForm.SearchText;
                    m_SearchResultsForm.MatchTheWholeWord = oSearchForm.MatchTheWholeWord;
                    m_SearchResultsForm.SearchInComments = oSearchForm.SearchInComments;
                    m_SearchResultsForm.SearchInStrings = oSearchForm.SearchInStrings;
                    m_SearchResultsForm.DoSearch();
                    WindowList.Instance().FocusWindow("All", "Search", "Search", null);

//                    this.m_SourceList[strWindowKey].Focus();
                    m_SearchResultsForm.Show();
                }

            }

        }

        private void closeAllDocumentsToolStripMenuItem_Click(object sender, EventArgs e)
        {
            // Window | Close All
            //MessageBox.Show("not impl");
            CloseAllDocuments();
        }

        private void CloseAllDocuments()
        {
            WindowList.Instance().CloseAll();
        }


        private void newQueryToolStripMenuItem_Click(object sender, EventArgs e)
        {
            //this.queryToolStripMenuItem_Click(sender, e);
        }

        private void newQueryCountRowsToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                // Database | New Query [Count rows]
                this.Cursor = Cursors.WaitCursor;
                SourceDatabase oSourceDb = UserSettings.Instance().getSourceDatabase(
                        UserSettings.Instance().CurrentDbNickName
                    );

                if (oSourceDb != null)
                {
                    string strNewQueryName;// = oSourceDb.BaseDirectory + "\\Queries\\" +
                        //oSourceDb.SysObjects.NewQueryName();

                    DBSourceToolsLib.SourceDatabaseLoader oLoader = new SourceDatabaseLoader(
                        this, DBSourceToolsLib.Commands.DatabaseCommandTypes.NewQuery);

                    oLoader.Execute(ref oSourceDb, null);
                    strNewQueryName = oLoader.NewQueryName;
                    if (oLoader.HasErrors())
                        throw new Exception(oLoader.GetErrorMessage());


                    this.oDBExplorer.UpdateTreeView(oSourceDb.NickName);

                    TextEditorForm oTextForm = new TextEditorForm(oSourceDb.NickName, "Queries", strNewQueryName
                        , DBSourceToolsLib.SysObjects.QueryType.CountDataQuery, null);
                    //oTextForm.RegisterInterestInSourceEditor(this);
                    string strWindowKey = oSourceDb.NickName + ".Queries." + strNewQueryName;

                    WindowList.Instance().AddWindow(strWindowKey, oTextForm);
                    //this.m_SourceList.Add(strWindowKey, oTextForm);
                    oTextForm.Show(this.m_dockPanelMain);

                }

            }
            catch (Exception ex)
            {
                DBSourceToolsLib.SysObjects.UI.Forms.ErrorForm oError =
                    new DBSourceToolsLib.SysObjects.UI.Forms.ErrorForm(ex.ToString());
                oError.ShowDialog(this);

            }
            this.Cursor = Cursors.Default;

        }

        private void newDeploymentTargetToolStripMenuItem_Click(object sender, EventArgs e)
        {
            // Database | Add | New Deployment Target
            try
            {
                if (UserSettings.Instance().DatabaseProject == null)
                {
                    MessageBox.Show("Deployment Targets can only be added to Source Databases.  Please create a Database Project File>New>Project before adding a Deployment Target to a Source Database.");
                    return;
                }

                DBHelper oHelper = new DBHelper();
                oHelper.NewDeploymentTarget(this);
                this.oDBExplorer.UpdateTreeViewDatabases();
            }   catch (Exception ex)
            {
                DBSourceToolsLib.SysObjects.UI.Forms.ErrorForm oError =
                    new DBSourceToolsLib.SysObjects.UI.Forms.ErrorForm(ex.ToString());
                oError.ShowDialog(this);

//                MessageBox.Show(ex.ToString());
            }

        }

        private void newSourceDatabaseToolStripMenuItem_Click(object sender, EventArgs e)
        {
            // first check if there is a database project
            try
            {
                if (UserSettings.Instance().DatabaseProject == null)
                {
                    MessageBox.Show("Please create a Database Project File>New>Project before adding a Source Database.");
                    return;
                }
                // Database | Add | New Source Database
                DBSourceToolsLib.DatabaseProjectUI.NewDatabaseForm oNewDbForm = new DBSourceToolsLib.DatabaseProjectUI.NewDatabaseForm(true, false);

                if (oNewDbForm.ShowDialog(this) == DialogResult.OK)
                {
                    DBConnectionLib.Database oNewSourceDb = oNewDbForm.GetDatabaseObject();
                    UserSettings.Instance().DatabaseProject.AddNewDatabase(oNewSourceDb);
                    UserSettings.Instance().CurrentDbNickName = oNewSourceDb.NickName;
                    UserSettings.Instance().SaveConfig();
                    UserSettings.Instance().DatabaseProject.WriteProjectFile();

                    if (MessageBox.Show(this, "Load Database" + oNewSourceDb.NickName + " now ?",
                        "Load Database ", MessageBoxButtons.YesNo) == DialogResult.Yes)
                    {
                        this.Cursor = Cursors.WaitCursor;

                        DBSourceToolsLib.SourceDatabase oSource
                            = UserSettings.Instance().getSourceDatabase(oNewSourceDb.NickName);

                        DBSourceToolsLib.SourceDatabaseLoader oSourceLoader =
                            new DBSourceToolsLib.SourceDatabaseLoader(this,
                                DBSourceToolsLib.Commands.DatabaseCommandTypes.LoadFromDatabase);

                        oSourceLoader.Execute(ref oSource, null);
                        if (oSourceLoader.HasErrors())
                            throw new Exception(oSourceLoader.GetErrorMessage());

                        DBSourceToolsLib.SourceDatabaseWriter oSourceWriter =
                            new SourceDatabaseWriter(this, DBSourceToolsLib.Commands.DatabaseCommandTypes.WriteToDisk
                                , UserSettings.Instance().DatabaseProject);
                        oSourceWriter.Execute(ref oSource, null);
                        if (oSourceWriter.HasErrors())
                            throw new Exception(oSourceWriter.GetErrorMessage());


                        //this.oDBExplorer.UpdateTreeView(oSource.NickName);
                        this.Cursor = Cursors.Default;
                    }

                    this.oDBExplorer.UpdateTreeViewDatabases();
                    UpdateToobar_DatabaseList();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }

        }

        private void queryToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            // Database | New Query | Query
            NewQueryHelper.NewQuery(DBSourceToolsLib.Commands.DatabaseCommandTypes.NewQuery, this);
//            this.queryToolStripMenuItem_Click(sender, e);

        }

        private void countRowsToolStripMenuItem_Click(object sender, EventArgs e)
        {
            NewQueryHelper.NewQuery(DBSourceToolsLib.Commands.DatabaseCommandTypes.CountDataQuery, this);
            // Database | New Query [Count rows]

        }

        private void newTableToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            // Database | New Query | New Table
            NewQueryHelper.NewQuery(DBSourceToolsLib.Commands.DatabaseCommandTypes.NewTableQuery, this);
        }


        private void newDatabaseToolStripMenuItem_Click(object sender, EventArgs e)
        {
            // Database | New Query | New Database
            RenameForm oNewName = new RenameForm("New Database Name");
            if (oNewName.ShowDialog(this) == DialogResult.OK)
            {
                NewQueryHelper.NewQuery(DBSourceToolsLib.Commands.DatabaseCommandTypes.NewDatabase, this, oNewName.NewName);
            }
        }

        private void loadFromDatabaseToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            // Database | Refresh | Load From database
            try
            {
                this.Cursor = Cursors.WaitCursor;

                DBHelper oHelper = new DBHelper();
                oHelper.LoadFromDatabase(this, UserSettings.Instance().CurrentDbNickName);

                this.Cursor = Cursors.Default;

                this.oDBExplorer.UpdateTreeView(UserSettings.Instance().CurrentDbNickName);
            }   catch (Exception ex)
            {
                DBSourceToolsLib.SysObjects.UI.Forms.ErrorForm oError =
                    new DBSourceToolsLib.SysObjects.UI.Forms.ErrorForm(ex.ToString());
                oError.ShowDialog(this);

//                MessageBox.Show(ex.ToString());
            }

        }

        private void loadFromDiskToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            // Database | Refresh | Load From Disk
            try
            {
                this.Cursor = Cursors.WaitCursor;
                DBHelper oHelper = new DBHelper();
                oHelper.LoadFromDisk(this, UserSettings.Instance().CurrentDbNickName);

                this.Cursor = Cursors.Default;

                this.oDBExplorer.UpdateTreeView(UserSettings.Instance().CurrentDbNickName);
            }   catch (Exception ex)
            {
                DBSourceToolsLib.SysObjects.UI.Forms.ErrorForm oError =
                    new DBSourceToolsLib.SysObjects.UI.Forms.ErrorForm(ex.ToString());
                oError.ShowDialog(this);

//                MessageBox.Show(ex.ToString());
            }

        }

        #region old code moved to NewQueryHelper
        //private void NewQuery(DBSourceToolsLib.Commands.DatabaseCommandTypes queryType, string strParams)
        //{
        //    try
        //    {
        //        this.Cursor = Cursors.WaitCursor;
        //        SourceDatabase oSourceDb = UserSettings.Instance().getSourceDatabase(
        //                UserSettings.Instance().CurrentDbNickName
        //            );

        //        if (oSourceDb != null)
        //        {
        //            string strNewQueryName;// = oSourceDb.SysObjects.NewQueryName();

        //            DBSourceToolsLib.SourceDatabaseLoader oLoader = new SourceDatabaseLoader(
        //                this, queryType);

        //            oLoader.Execute(ref oSourceDb, strParams);
        //            if (oLoader.HasErrors())
        //                throw new Exception(oLoader.GetErrorMessage());
        //            strNewQueryName = oLoader.NewQueryName;

        //            this.oDBExplorer.UpdateTreeView(oSourceDb.NickName);

        //            WindowList.Instance().ShowWindow(new TreeNodeTag(oSourceDb.NickName, "File", oLoader.NewQueryFileName, null));

        //            //NotifyEvent(UserSettings.Instance().CurrentDbNickName,
        //            //        "File", oLoader.NewQueryFileName,
        //            //        DBSourceToolsLib.Interfaces.DBExplorerObserverEvent.SelectChanged, "Generated");

        //        }

                
        //    }
        //    catch (Exception ex)
        //    {
        //        DBSourceToolsLib.SysObjects.UI.Forms.ErrorForm oError =
        //            new DBSourceToolsLib.SysObjects.UI.Forms.ErrorForm(ex.ToString());
        //        oError.ShowDialog(this);

        //        //                MessageBox.Show(ex.ToString());
        //    }
        //    finally
        //    {
        //        this.Cursor = Cursors.Default;
        //    }

        //}
        #endregion

        private void OnSelect_CurrentDb(object sender, EventArgs e)
        {
            string strCurrentDBNick = (string)m_toolStripComboBox_CurrentDB.SelectedItem;
            UserSettings.Instance().CurrentDbNickName = strCurrentDBNick;
        }

        private void sourceDatabaseToolStripMenuItem_Click(object sender, EventArgs e)
        {
            // Database | Delete | Source Database
            try
            {
                if (MessageBox.Show(this, String.Format("Delete Source database : {0} from Project ?",
                    UserSettings.Instance().CurrentDbNickName), "Delete Source", MessageBoxButtons.YesNo) == DialogResult.Yes)
                {
                    UserSettings.Instance().DatabaseProject.DeleteDatabase(
                        UserSettings.Instance().CurrentDbNickName);
                    this.oDBExplorer.UpdateTreeViewDatabases();
                    UpdateToobar_DatabaseList();
                    UserSettings.Instance().DatabaseProject.WriteProjectFile();
                    UserSettings.Instance().SaveConfig();
                }
            }
            catch (Exception ex)
            {
                DBSourceToolsLib.SysObjects.UI.Forms.ErrorForm oError =
                    new DBSourceToolsLib.SysObjects.UI.Forms.ErrorForm(ex.ToString());
                oError.ShowDialog(this);

//                MessageBox.Show(ex.ToString());
            }
        }

        private void newProcToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            NewQueryHelper.NewQuery(DBSourceToolsLib.Commands.DatabaseCommandTypes.NewProc, this);
        }

        private void closeProjectToolStripMenuItem_Click(object sender, EventArgs e)
        {
            // File | Close Project
            CloseAllDocuments();
            UserSettings.Instance().CloseProject();
            oDBExplorer.UpdateTreeViewDatabases();
            UpdateToobar_DatabaseList();
            //WindowList.Instance().RemoveWindow("SrvExplorer", null, null);
            //oServerExplorer = null;
        }

        private void aboutToolStripMenuItem_Click(object sender, EventArgs e)
        {
            AboutBox oAbout = new AboutBox();
            oAbout.ShowDialog(this);
        }

        private void newFunctionToolStripMenuItem_Click(object sender, EventArgs e)
        {
            NewQueryHelper.NewQuery(DBSourceToolsLib.Commands.DatabaseCommandTypes.NewFunction, this);
        }

        private void excelSpreadsheetToolStripMenuItem_Click(object sender, EventArgs e)
        {

            try
            {
                this.m_openFileDialog1.Filter = "Excel files (*.xls)|*.xls";
                if (this.m_openFileDialog1.ShowDialog(this) == DialogResult.OK)
                {

                    NewQueryHelper.NewQuery(DBSourceToolsLib.Commands.DatabaseCommandTypes.NewTableFromExcel, this, this.m_openFileDialog1.FileName);

                }
            }
            catch (Exception ex)
            {
                DBSourceToolsLib.SysObjects.UI.Forms.ErrorForm oError =
                    new DBSourceToolsLib.SysObjects.UI.Forms.ErrorForm(ex.ToString());
                oError.ShowDialog(this);

                //                MessageBox.Show(ex.ToString());
            }
            
        }


        private void compareSchemasToolStripMenuItem_Click(object sender, EventArgs e)
        {

            try
            {
                CompareDatabasesForm oCompForm = new CompareDatabasesForm();
                if (oCompForm.ShowDialog(this) == DialogResult.OK)
                {
                    oDBExplorer.UpdateTreeViewDatabases();

                    DatabaseEx oSourceDbEx = UserSettings.Instance().DatabaseProject.GetDatabaseEx(
                        oCompForm.SourceDatabaseNick);
                    DatabaseEx oTargetDbEx = UserSettings.Instance().DatabaseProject.GetDatabaseEx(
                        oCompForm.TargetDatabaseNick);

                    if (!oSourceDbEx.CanCompare() || !oTargetDbEx.CanCompare())
                    {
                        MessageBox.Show("Schema Comparison is not supported on SQL2000 databases");
                    }
                    else
                    {

                        SourceDatabase oSourceDb = new SourceDatabase(oSourceDbEx, false);

                        this.Cursor = Cursors.WaitCursor;

                        TreeNodeTag oCompareNode = new TreeNodeTag(oSourceDbEx.NickName, "CompareResults",
                            oSourceDbEx.NickName + "v" + oCompForm.TargetDatabaseNick, null);

                        WindowList.Instance().ShowWindow(oCompareNode, oCompForm.TargetDatabaseNick);
                    }

                    this.Cursor = Cursors.Default;
                    // TODO : COMPLETE 1.2.0.8 MainForm Compare Schemas

                }
            }
            catch (Exception ex)
            {
                DBSourceToolsLib.SysObjects.UI.Forms.ErrorForm oError =
                    new DBSourceToolsLib.SysObjects.UI.Forms.ErrorForm(ex.ToString());
                oError.ShowDialog(this);

            }
            this.Cursor = Cursors.Default;

        }

        private void serverExplorerToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (oServerExplorer == null)
            {
                oServerExplorer = new SrvExplorer();
                //WindowList.Instance().AddWindow("SrvExplorer..", oServerExplorer);
                oServerExplorer.Show(this.m_dockPanelMain);
                //oServerExplorer.RegisterInterestInDbExplorer(this);
            }

            //WindowList.Instance().FocusWindow("SrvExplorer", null, null, null);

            //WindowList.Instance().ShowWindow(new TreeNodeTag("SrvExplorer", null, null, null));
            //if (oServerExplorer != null)
            oServerExplorer.ReloadDatabaseList();
            oServerExplorer.Show();

        }

        private void defaultSettingsToolStripMenuItem_Click(object sender, EventArgs e)
        {
            DefaultSettings oDefaultSettings = new DefaultSettings();
            if (oDefaultSettings.ShowDialog(this) == DialogResult.OK)
            {
            }
        }



        public void NotifyEvent(TreeNodeTag oTreeNodeTag, Interfaces.WindowListObserverEvent oEvent)
        {
            m_toolStripComboBox_CurrentDB.SelectedItem = oTreeNodeTag.DatabaseName;
            if (oTreeNodeTag.ObjectType.Equals("File"))
                this.m_toolStripStatusLabel.Text = "Current File : " + oTreeNodeTag.ObjectName;
            else
                this.m_toolStripStatusLabel.Text = "Current Base Directory : " + UserSettings.Instance().ProjectBaseDirectory;
        }
    }
}
